#include <curl/curl.h>
#include <cjson/cJSON.h>


//回调函数
size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;
    //result是请求后响应回来的json字符串 使用cjson解析json字符串
    cJSON *root = cJSON_Parse(result); //将json字符串转为json对象
    if(root != NULL)
    {
        cJSON *successjson = cJSON_GetObjectItemCaseSensitive(root,"success");
        cJSON *codejson = cJSON_GetObjectItemCaseSensitive(root,"code");
        cJSON *messagejson = cJSON_GetObjectItemCaseSensitive(root,"message");
        printf("操作成功 success=%d,code=%d,message=%s\n",successjson->valueint,codejson->valueint,messagejson->valuestring);   
    }
    printf("%s\n",result);
    return realsize;
}

int main(int argc, char const *argv[])
{
    //1.初始化curl得到curl对象
    CURL *curl = curl_easy_init();
    if (curl)
    {
        //2.设置curl路径和回调函数
        curl_easy_setopt(curl,CURLOPT_URL,"http://47.109.65.208/config.json");
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writeCallback);

        //3.发起请求
        CURLcode code = curl_easy_perform(curl);
        //发起请求是否成功
        if(code != CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(code));
        }

        //4.清空curl
        curl_easy_cleanup(curl);
    }
    return 0;
}

